const fs = require('fs')
const path = require('path')
const ejs = require('ejs')
const url = require('url');

function getFileMime(extname){
    // 使用同步方法返回数据
    var data = fs.readFileSync('./处理文件后缀名/mime.json');
    let mimeobj=JSON.parse(data.toString());
    return mimeobj[extname];
}

let app = {
    static:(req,res,staticPath)=>{
        let pathname = req.url;
        const extname = path.extname(pathname)
        if(pathname != '/favicon.ico'){
            try{
                let data = fs.readFileSync('.'+pathname)
                if(data){
                    let mime =getFileMime(extname)
                    res.writeHead(200, {'Content-Type': `${mime};charset=utf-8`});
                    res.end(data)
                    return true
                }
            }catch(err){
                return false;
            }   
        }
    },
    login:(req,res)=>{
        ejs.renderFile('./views/form.ejs',{},(err,data)=>{
            res.writeHead(200,{'Content-Type':'text/html;charset="utf-8"'});
            res.end(data)
        })
    },
    news:(req,res)=>{
        res.end('news');
    },
    doLogin:(req,res)=>{
        // 获取 post 传值
        let postData = '';
        req.on('data',(chunk)=>{
            postData+=chunk;
        })
        req.on('end',()=>{
            console.log(postData);
            res.end(postData)
        })
    },
    error:(req,res)=>{
        res.end('error');
    },
}

module.exports = app;